<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Frontend extends CI_Controller {

    public $render_data;

    function __construct() {
        parent::__construct();
        if ($this->uri->segment(1) == 'frontend') {
            show_404();
        }

        // Check Login //
        $this->render_data['user_id'] = null;
        $this->render_data['is_admin'] = 0;
        $this->render_data['fb_id'] = 0;
        $this->render_data['fullname'] = 0;

        if ($this->session->userdata('user_id')) {

            $this->render_data['user_id'] = $this->session->userdata('user_id');
            $this->render_data['fb_id'] = $this->session->userdata('fb_id');
            $this->render_data['is_admin'] = $this->session->userdata('is_admin');
            $this->render_data['fullname'] = $this->session->userdata('fullname');
        }
    }

    function home() {
        $this->load->library(array('template', 'carabiner'));

        $this->template->write('title', 'หน้าแรก | ' . WEB_TITLE);



        $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);

        $this->render_data['is_voted'] = TRUE;
        if ($this->render_data['user_id']) {
            $this->load->model('campaign_join_model', 'campaign_join');
            $this->render_data['recent_voted_list'] = $this->campaign_join->get_recent_voted_candidate($this->render_data['user_id']);

            // Get Most Active Candidate //
            $this->render_data['active_candidate'] = $this->campaign_join->get_active_candidate();

            //Add Activities//
            if ($this->render_data['active_candidate'] !== FALSE) {
                $user_activities = $this->db->select('voted_at,viewed_at')->where('user_id', $this->session->userdata('user_id'))->where('campaign_join_id', $this->render_data['active_candidate']['candidate_id'])->get('campaign_activities')->row_array();
                if (!$user_activities) {
                    $data_save = array(
                        'user_id' => $this->session->userdata('user_id'),
                        'campaign_id' => $this->render_data['active_candidate']['campaign_id'],
                        'campaign_join_id' => $this->render_data['active_candidate']['candidate_id'],
                        'view' => 1,
                        'viewed_at' => time()
                    );
                    $this->db->insert('campaign_activities', $data_save);
                    $this->render_data['is_voted'] = FALSE;
                } else {
                   
                    $this->render_data['is_voted'] = $user_activities['voted_at'] != 0 ? TRUE : FALSE;
                    
                    // If Action is more than 1 hours //
                    if (($user_activities['viewed_at'] + 3600) < time()) {
                        $this->db->set('view', 'view+1', FALSE)
                                ->where('user_id', $this->session->userdata('user_id'))
                                ->where('campaign_id', $this->render_data['active_candidate']['campaign_id'])
                                ->where('campaign_join_id', $this->render_data['active_candidate']['candidate_id'])
                                ->update('campaign_activities');
                    }
                }

                // Load Galleria //

                $this->render_data['js_indy'][] = 'galleria/galleria-1.2.9.min.js';
                $this->render_data['js_indy'][] = 'galleria/themes/classic/galleria.classic.min.js';
                $this->render_data['css_indy'][] = '../js/galleria/themes/classic/galleria.classic.css';
            }
        }


        // Get Recent and Coming List //
        $this->load->model('campaign_model', 'campaign');
        $this->render_data['campaign_recent_list'] = $this->campaign->list_recent_campaign();
        $this->render_data['campaign_coming_list'] = $this->campaign->list_coming_campaign();

        //Create a new slideshow file//
        if (!is_file('./uploads/slideshow')) {
            file_put_contents('./uploads/slideshow', serialize(array()));
        }


        $this->render_data['slideshow_list'] = unserialize(file_get_contents('./uploads/slideshow'));


        $this->template->write_view('content', 'home', $this->render_data);
        $this->template->render();
    }

    // หน้า รายการที่กำลังรับสมัคร //
    /*
      function list_campaign_waiting() {
      $this->load->library(array('template', 'carabiner'));
      $this->template->write('title', 'รายการที่กำลังเปิดรับสมัคร - ' . WEB_TITLE);
      $this->render_data['count_register_list'] = $this->_get_register_list_count();

      // Get Waiting List //
      $this->load->model('campaign_model', 'campaign');
      $this->render_data['campaign_list'] = $this->campaign->list_waiting_campaign();


      $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);
      $this->template->write_view('content', 'list_campaign_waiting', $this->render_data);
      $this->template->render();
      } */

    // หน้า รายการที่กำลังรับสมัคร //
    function list_campaign_announce() {
        $this->load->library(array('template', 'carabiner'));
        $this->template->write('title', 'รายการที่ประกาศผลแล้ว | ' . WEB_TITLE);


        // Get Announce List //
        $this->load->model('campaign_model', 'campaign');
        $this->render_data['campaign_list'] = $this->campaign->list_announce_campaign();


        $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);
        $this->template->write_view('content', 'list_campaign_announce', $this->render_data);
        $this->template->render();
    }

    // จัดการ Hash //
    private function _get_campaign_hash($hash) {
        // Get Campaign //
        $this->load->model('campaign_model', 'campaign');
        $this->render_data['campaign'] = $this->campaign->get_campaign_by_hash($hash);

        // Validate Hash //
        if (!$this->render_data['campaign']) {
            show_404();
        }

        return $hash;
    }

    // หน้า ลงทะเบียน //
    private function _extract_youtube_id($link) {
        parse_str(parse_url($link, PHP_URL_QUERY), $my_array_of_vars);
        $yt_id = trim($my_array_of_vars['v']);

        return $yt_id;
    }

    function _check_youtube_url($str) {
        $str = trim($str);

        $yt_id = $this->_extract_youtube_id($str);

        if (!$yt_id) {
            $this->form_validation->set_message('_check_youtube_url', 'Youtube Error');
            return FALSE;
        }

        $curlSession = curl_init();
        curl_setopt($curlSession, CURLOPT_URL, "http://gdata.youtube.com/feeds/api/videos/{$yt_id}?v=2&alt=json");
        curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);

        $jsonData = json_decode(curl_exec($curlSession));
        curl_close($curlSession);

        if ($jsonData) {
            return TRUE;
        }

        $this->form_validation->set_message('_check_youtube_url', 'Youtube Error');
        return FALSE;
    }

    function delete_campaign_register($hash, $candidate_id) {

        $campaign_id = hashids_decrypt($hash);
        $candidate_id = hashids_decrypt($candidate_id);
        if ($campaign_id && $candidate_id) {
            if ($this->render_data['is_admin'] == 1) {
                $this->db->where('id', $candidate_id)->delete('campaign_joins');
            } else {
                $this->db->where('id', $candidate_id)->where('user_id', $this->render_data['user_id'])->delete('campaign_joins');
            }
            if ($this->db->affected_rows() > 0) {
                // Delete Image //
                if (is_dir('./uploads/register_image/' . $candidate_id . '/')) {
                    $this->load->helper('file');
                    delete_files('./uploads/register_image/' . $candidate_id . '/', TRUE);
                    rmdir('./uploads/register_image/' . $candidate_id . '/');
                }
            }
            // Add candidate count to campaigns //
            $this->db->set('candidate_amount', 'candidate_amount-1', FALSE)->where('id', $campaign_id)->update('campaigns');
            $this->session->set_flashdata('deleted', TRUE);
            redirect(base_url() . 'contest/' . $hash . '/register');
        } else {
            redirect(base_url() . 'contest/' . $hash);
        }
    }

    // หน้า กิจกรรม / การแข่งขัน //
    function get_campaign($hash, $candidate_number = null) {
        $this->render_data['hash'] = $this->_get_campaign_hash($hash);

        if ($this->render_data['campaign']['status'] == 'pending') {
            redirect(base_url() . 'contest/' . $hash . '/description');
        }

        $this->load->library(array('template', 'carabiner'));

        $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);


        // Get Random Competitor //
        $this->load->model('campaign_join_model', 'campaign_join');

        session_start();

        if (isset($_SESSION["highlight_" . $hash]) && $_SESSION["highlight_" . $hash] === TRUE) {
            $this->render_data['show_highlight'] = FALSE;
        } else {
            $token = uniqid();
            $_SESSION["highlight_" . $hash] = $token;
            $this->render_data['show_highlight'] = $token;
        }


        // If Get Candidate //
        if ($this->render_data['candidate'] = $this->campaign_join->get_candidate($this->render_data['campaign']['id'], $candidate_number)) {

            // Redirect ใหม่ สำหรับ เข้ามาหน้าเปล่า //
            if ($candidate_number == null) {
                redirect(base_url() . 'contest/' . $hash . '/' . $this->render_data['candidate']['candidate_number']);
                return;
            }


            $this->template->write('title', 'ผลงานชื่อ ' . $this->render_data['candidate']['title'] . ' โดย ' . $this->render_data['candidate']['firstname'] . ' ' . $this->render_data['candidate']['lastname'] . ' < ' . $this->render_data['campaign']['title'] . ' | ' . WEB_TITLE);
            $this->render_data['is_my_register'] = FALSE;

            // Check if this user is registered //
            if ($this->render_data['user_id'] == $this->render_data['candidate']['user_id']) {
                $this->render_data['is_my_register'] = TRUE;
            }


            // Add Activities //
            if ($this->render_data['user_id'] > 0) {

                $user_activities = $this->db->select('voted_at,viewed_at')->where('user_id', $this->session->userdata('user_id'))->where('campaign_join_id', $this->render_data['candidate']['id'])->get('campaign_activities')->row_array();
                if (!$user_activities) {
                    $data_save = array(
                        'user_id' => $this->session->userdata('user_id'),
                        'campaign_id' => $this->render_data['campaign']['id'],
                        'campaign_join_id' => $this->render_data['candidate']['id'],
                        'view' => 1,
                        'viewed_at' => time()
                    );
                    $this->db->insert('campaign_activities', $data_save);
                    $this->render_data['is_voted'] = FALSE;
                } else {
                    $this->render_data['is_voted'] = $user_activities['voted_at'] != 0 ? TRUE : FALSE;

                    // If Action is more than 1 hours //
                    if (($user_activities['viewed_at'] + 3600) < time()) {
                        $this->db->set('view', 'view+1', FALSE)
                                ->where('user_id', $this->session->userdata('user_id'))
                                ->where('campaign_id', $this->render_data['campaign']['id'])
                                ->where('campaign_join_id', $this->render_data['candidate']['id'])
                                ->update('campaign_activities');
                    }
                }
            } else {
                $this->render_data['is_voted'] = TRUE;
            }

            // Load Galleria //
            if ($this->render_data['campaign']['candidate_image'] > 0 || $this->render_data['campaign']['candidate_vdo'] > 0) {
                $this->render_data['js_indy'][] = 'galleria/galleria-1.2.9.min.js';
                $this->render_data['js_indy'][] = 'galleria/themes/classic/galleria.classic.min.js';
                $this->render_data['css_indy'][] = '../js/galleria/themes/classic/galleria.classic.css';
            }



            // OG for facebook //
            $this->render_data['og']['url'] = base_url() . 'contest/' . $hash . '/' . $this->render_data['candidate']['candidate_number'];
            $this->render_data['og']['image'] = base_url() . 'uploads/sponsor_logo/' . $this->render_data['campaign']['logo'];

            // Get Thumbnail of Youtube
            if ($this->render_data['campaign']['candidate_vdo'] > 0) {
                $register_content = unserialize($this->render_data['candidate']['register_content']);
                $this->render_data['og']['image'] = 'http://i.ytimg.com/vi/' . $register_content[0] . '/hqdefault.jpg';
            }
        } else { // ไม่เจอผู้เข้าแข่งขัน //
            // OG for facebook //
            $this->render_data['og']['url'] = base_url() . 'contest/' . $hash . '/' . $this->render_data['candidate']['candidate_number'];
            $this->render_data['og']['image'] = base_url() . 'uploads/sponsor_logo/' . $this->render_data['campaign']['logo'];
            $this->template->write('title', 'ไม่พบผู้เข้าแข่งขัน | ' . WEB_TITLE);
            $this->render_data['not_found'] = TRUE;
        }


        // Get Another Candidates //
        $this->render_data['other_candidate_list'] = $this->campaign_join->get_other_candidate_list($this->render_data['campaign']['id'], $this->render_data['candidate']['candidate_number']);

        // Get Not View Candidates //
        if ($this->render_data['user_id']) {
            $this->render_data['noview_candidate_list'] = $this->campaign_join->get_noview_candidate_list($this->render_data['campaign']['id'], $this->render_data['user_id']);
        } else {
            $this->render_data['noview_candidate_list'] = array();
        }



        $this->render_data['campaign_content'] = $this->load->view('campaign_battle', $this->render_data, TRUE);

        // Load Code Mirror //
        if ($this->render_data['is_admin'] == 1) {
            $this->render_data['js'][] = 'jqueryui.js';
            $this->render_data['js'][] = 'codemirror.js';
            $this->render_data['js'][] = 'codemirror_mode/css/css.js';
            $this->render_data['css'][] = 'codemirror.css';
            $this->render_data['css'][] = 'codemirror_theme/ambiance.css';
        }




        $this->template->write_view('content', 'campaign_wrapper', $this->render_data);
        $this->template->render();
    }

    function get_campaign_description($hash) {
        $this->render_data['hash'] = $this->_get_campaign_hash($hash);

        $this->load->library(array('template', 'carabiner'));
        $this->template->write('title', 'รายละเอียดกิจกรรม < ' . $this->render_data['campaign']['title'] . ' | ' . WEB_TITLE);


        $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);

        $this->render_data['campaign_content'] = $this->load->view('campaign_description', $this->render_data, TRUE);


        // Load Code Mirror //
        if ($this->render_data['is_admin'] == 1) {
            $this->render_data['js'][] = 'jqueryui.js';
            $this->render_data['js'][] = 'codemirror.js';
            $this->render_data['js'][] = 'codemirror_mode/css/css.js';
            $this->render_data['css'][] = 'codemirror.css';
            $this->render_data['css'][] = 'codemirror_theme/ambiance.css';
        }

        // OG for facebook //
        $this->render_data['og']['url'] = base_url() . 'contest/' . $hash . '/description';
        $this->render_data['og']['image'] = base_url() . 'uploads/sponsor_logo/' . $this->render_data['campaign']['logo'];

        $this->template->write_view('content', 'campaign_wrapper', $this->render_data);
        $this->template->render();
    }

    function _check_image_upload($str) {

        // Uploading Logo //
        $config['upload_path'] = './register_tmp/' . $this->render_data['timestamp'] . '/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['encrypt_name'] = TRUE;

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('image_' . $this->render_data['image_flag'])) {
            $this->form_validation->set_message('_check_image_upload', $this->upload->display_errors());
            echo $this->upload->display_errors();
            return false;
        } else {

            $this->render_data['image_flag']++;
            $data = $this->upload->data();
            $this->render_data['images'][] = $data['file_name'];
            return true;
        }
    }

    function get_campaign_register($hash) {

        $this->render_data['hash'] = $this->_get_campaign_hash($hash);

        // Check if this campaign is in starting status //
        if ($this->render_data['campaign']['status'] != 'starting') {
            redirect('/');
        }

        // Check if user is registered //
        $this->load->model('campaign_join_model', 'campaign_join');
        $candidate_number = $this->campaign_join->get_candidate_number($this->render_data['campaign']['id'], $this->render_data['user_id']);
        if ($candidate_number !== FALSE) {
            $this->session->set_flashdata('register', TRUE);
            redirect(base_url() . 'contest/' . $hash . '/' . $candidate_number);
        }

        $this->load->library(array('template', 'carabiner', 'form_validation'));
        if ($_POST) {
            $this->form_validation->set_rules('title', 'Title', 'required|max_length[100]|trim');
            $this->form_validation->set_rules('description', 'Description', 'required|trim');

            // Check Youtube //
            if ($this->render_data['campaign']['candidate_vdo'] > 0) {
                for ($i = 1; $i <= $this->render_data['campaign']['candidate_vdo']; $i++) {
                    $this->form_validation->set_rules('vdo_' . $i, 'VDO', 'required|trim|callback__check_youtube_url');
                }
            }
            // Check Image //
            if ($this->render_data['campaign']['candidate_image'] > 0) {
                $this->render_data['image_flag'] = 1;
                $this->render_data['timestamp'] = time();
                mkdir('./register_tmp/' . $this->render_data['timestamp']);
                for ($i = 1; $i <= $this->render_data['campaign']['candidate_image']; $i++) {
                    $this->form_validation->set_rules('image_' . $i, 'Image', 'callback__check_image_upload');
                }
            }
            // Check Text //
            if ($this->render_data['campaign']['candidate_text'] > 0) {
                for ($i = 1; $i <= $this->render_data['campaign']['candidate_text']; $i++) {
                    $this->form_validation->set_rules('text_' . $i, 'Text', 'required');
                }
            }

            if ($this->form_validation->run() !== FALSE) {
                $data_save = array(
                    'title' => $this->input->post('title', TRUE),
                    'description' => $this->input->post('description', TRUE),
                    'user_id' => $this->render_data['user_id'],
                    'campaign_id' => $this->render_data['campaign']['id'],
                );
                // Save Youtube //
                if ($this->render_data['campaign']['candidate_vdo'] > 0) {
                    $vdo_array = array();
                    for ($i = 1; $i <= $this->render_data['campaign']['candidate_vdo']; $i++) {
                        $vdo_array[] = $this->_extract_youtube_id($this->input->post('vdo_' . $i));
                    }
                    $data_save['register_content'] = serialize($vdo_array);
                }

                // Save Images //
                if ($this->render_data['campaign']['candidate_image'] > 0) {
                    $data_save['register_content'] = serialize($this->render_data['images']);
                }

                // Save Text //
                if ($this->render_data['campaign']['candidate_text'] > 0) {
                    $text_array = array();
                    for ($i = 1; $i <= $this->render_data['campaign']['candidate_text']; $i++) {
                        $text_array[] = strip_tags($this->input->post('text_' . $i), '<p><strike><em><strong><ol><li><ul><hr>');
                    }
                    $data_save['register_content'] = serialize($text_array);
                }



                // Save data //
                $this->load->model('campaign_join_model', 'campaign_join');
                $insert_id = $this->campaign_join->add_campaign_join($data_save);



                // Move Images //
                if ($this->render_data['campaign']['candidate_image'] > 0) {
                    mkdir('./uploads/register_image/' . $insert_id);

                    foreach ($this->render_data['images'] as $image) {
                        copy('./register_tmp/' . $this->render_data['timestamp'] . '/' . $image, './uploads/register_image/' . $insert_id . '/' . $image);
                    }
                    $this->load->helper('file');
                    delete_files('./register_tmp/' . $this->render_data['timestamp'] . '/', TRUE);
                    rmdir('./register_tmp/' . $this->render_data['timestamp'] . '/');
                }
                $this->session->set_flashdata('register', TRUE);
                redirect(base_url() . 'contest/' . $hash . '/' . $insert_id);
            } else {
                if ($this->render_data['campaign']['candidate_image'] > 0) {
                    $this->load->helper('file');
                    delete_files('./register_tmp/' . $this->render_data['timestamp'] . '/', TRUE);
                    rmdir('./register_tmp/' . $this->render_data['timestamp'] . '/');
                }
            }
        }


        $this->template->write('title', 'สมัครแข่งขัน < ' . $this->render_data['campaign']['title'] . ' | ' . WEB_TITLE);
        $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);


        if ($this->session->userdata('user_id')) {
            $this->render_data['campaign_content'] = $this->load->view('campaign_register', $this->render_data, TRUE);
        } else {
            $this->render_data['campaign_content'] = $this->load->view('emergency_login', $this->render_data, TRUE);
        }

        // Load Code Mirror //
        if ($this->render_data['is_admin'] == 1) {
            $this->render_data['js'][] = 'jqueryui.js';
            $this->render_data['js'][] = 'codemirror.js';
            $this->render_data['js'][] = 'codemirror_mode/css/css.js';
            $this->render_data['css'][] = 'codemirror.css';
            $this->render_data['css'][] = 'codemirror_theme/ambiance.css';
        }

        // Load CKEDITOR IF TEXT //
        if ($this->render_data['campaign']['candidate_text'] > 0) {
            $this->render_data['js_indy'][] = 'ckeditor/ckeditor.js';
            $this->render_data['js_indy'][] = 'ckfinder/ckfinder.js';
        }

        // OG for facebook //
        $this->render_data['og']['url'] = base_url() . 'contest/' . $hash . '/register';
        $this->render_data['og']['image'] = base_url() . 'uploads/sponsor_logo/' . $this->render_data['campaign']['logo'];

        $this->template->write_view('content', 'campaign_wrapper', $this->render_data);
        $this->template->render();
    }

    function get_campaign_rank($hash) {
        $this->render_data['hash'] = $this->_get_campaign_hash($hash);

        $this->load->library(array('template', 'carabiner'));
        $this->template->write('title', 'จัดอันดับ < ' . $this->render_data['campaign']['title'] . ' | ' . WEB_TITLE);


        $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);

        $this->load->model('campaign_join_model', 'campaign_join');
        $this->render_data['candidate_list'] = $this->campaign_join->get_rank_candidate($this->render_data['campaign']['id']);

        $this->render_data['campaign_content'] = $this->load->view('campaign_rank', $this->render_data, TRUE);

        // Load Code Mirror //
        if ($this->render_data['is_admin'] == 1) {
            $this->render_data['js'][] = 'jqueryui.js';
            $this->render_data['js'][] = 'codemirror.js';
            $this->render_data['js'][] = 'codemirror_mode/css/css.js';
            $this->render_data['css'][] = 'codemirror.css';
            $this->render_data['css'][] = 'codemirror_theme/ambiance.css';
        }

        // Load Galleria //
        if ($this->render_data['campaign']['candidate_image'] > 0) {
            $this->render_data['js_indy'][] = 'galleria/galleria-1.2.9.min.js';
            $this->render_data['js_indy'][] = 'galleria/themes/classic/galleria.classic.min.js';
            $this->render_data['css_indy'][] = '../js/galleria/themes/classic/galleria.classic.css';
        }

        // OG for facebook //
        $this->render_data['og']['url'] = base_url() . 'contest/' . $hash . '/announce';
        $this->render_data['og']['image'] = base_url() . 'uploads/sponsor_logo/' . $this->render_data['campaign']['logo'];

        $this->template->write_view('content', 'campaign_wrapper', $this->render_data);
        $this->template->render();
    }

    function edit_my_profile() {
        if (!$this->render_data['user_id']) {
            redirect('/');
        }
        $this->load->library(array('template', 'carabiner', 'form_validation'));

        $this->template->write('title', 'แก้ไขโปรไฟล์ |' . WEB_TITLE);


        if ($_POST) {
            $this->form_validation->set_rules('firstname', 'firstname', 'required|max_length[50]|trim');
            $this->form_validation->set_rules('lastname', 'lastname', 'required|max_length[50]|trim');
            $this->form_validation->set_rules('telephone', 'telephone', 'max_length[50]|trim');
            if ($this->form_validation->run() !== FALSE) {
                // Update Profile //
                $update_data = array(
                    'firstname' => strip_tags($this->input->post('firstname', TRUE)),
                    'lastname' => strip_tags($this->input->post('lastname', TRUE)),
                    'telephone' => strip_tags($this->input->post('telephone', TRUE)),
                    'address' => strip_tags($this->input->post('address', TRUE)),
                );

                $this->db->where('id', $this->render_data['user_id'])->update('users', $update_data);
                $fullname = strip_tags($this->input->post('firstname', TRUE)) . ' ' . strip_tags($this->input->post('lastname', TRUE));
                // Update Session //
                $this->session->set_userdata(array('fullname' => $fullname));

                $this->session->set_flashdata('edit', TRUE);
                redirect('my-profile');
            }
        }

        // Get My Profile //
        $this->render_data['profile'] = $this->db->select('firstname,lastname,telephone,address,fb_id,birthday,email,created_at')->where('id', $this->render_data['user_id'])->get('users')->row_array();

        $this->template->write_view('main_nav', 'partials/main_nav', $this->render_data);

        $this->template->write_view('content', 'edit_my_profile', $this->render_data);
        $this->template->render();
    }

}
